package com.yulinlin.admin.common.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

public class TemplateUtil {


  static Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);

  static {
    StringTemplateLoader templateLoader = new StringTemplateLoader();
    configuration.setTemplateLoader(templateLoader);
    configuration.setDefaultEncoding("UTF-8");
  }

  /**
   * @param text 字符串模板
   * @param params 参数
   * @return
   */

  public static String renderString(String text, Object params) throws Exception{
    StringWriter stringWriter = new StringWriter();
    Template template =
        new Template("xx", text, configuration);
    template.process(params, stringWriter);
    return stringWriter.toString();
  }


  private static Configuration conf = new Configuration();

  static {
      conf.setClassForTemplateLoading(TemplateUtil.class, "/");
  }


  public static String renderTemplate(String templatePath, Map<String, Object> args) throws Exception {
    Template temp = conf.getTemplate(templatePath);
    temp.setEncoding("UTF-8");
    Writer out = new StringWriter(2048);
    temp.process(args, out);

    return out.toString();
  }
}
